#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
#import "webview.h"

// 前向声明
@class WebViewController;

// 定义一个协议，用于 WebViewController 和 WebViewWindowDelegate 之间的通信
@protocol WebViewControllerDelegate <NSObject>
- (BOOL)isPointInDragRegion:(NSPoint)point;
@end

// 添加窗口代理类来处理大小调整
@interface WebViewWindowDelegate : NSObject <NSWindowDelegate>
@property (nonatomic, assign) BOOL isResizing;
@property (nonatomic, assign) NSPoint initialMouseLocation;
@property (nonatomic, assign) NSRect initialFrame;
@property (nonatomic, assign) int resizeEdge; // 0=none, 1=top, 2=right, 3=bottom, 4=left, 5=topright, 6=bottomright, 7=bottomleft, 8=topleft
@property (nonatomic, weak) id<WebViewControllerDelegate> delegate; // 使用协议而不是具体类
@end

@implementation WebViewWindowDelegate
- (id)init {
    self = [super init];
    if (self) {
        _isResizing = NO;
        _resizeEdge = 0;
    }
    return self;
}

- (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)newFrame {
    return window.frame;
}

// 处理鼠标移动事件，检测是否在窗口边缘
- (void)mouseMovedOnWindow:(NSWindow *)window event:(NSEvent *)event {
    if (self.isResizing) return;
    
    NSPoint mouseLocation = [window convertPointFromScreen:[NSEvent mouseLocation]];
    NSRect frame = window.contentView.frame;
    
    // 边缘检测区域大小
    CGFloat edgeSize = 8.0;
    
    BOOL isOnLeftEdge = mouseLocation.x <= edgeSize;
    BOOL isOnRightEdge = mouseLocation.x >= frame.size.width - edgeSize;
    BOOL isOnBottomEdge = mouseLocation.y <= edgeSize;
    BOOL isOnTopEdge = mouseLocation.y >= frame.size.height - edgeSize;
    
    // 检查是否在拖拽区域内
    BOOL isInDragRegion = NO;
    if (self.delegate && [self.delegate respondsToSelector:@selector(isPointInDragRegion:)]) {
        isInDragRegion = [self.delegate isPointInDragRegion:mouseLocation];
    }
    
    // 如果在拖拽区域内，则不显示调整大小的光标，除非在窗口边缘
    if (isInDragRegion && !(isOnLeftEdge || isOnRightEdge || isOnTopEdge || isOnBottomEdge)) {
        [[NSCursor arrowCursor] set];
        self.resizeEdge = 0;
        return;
    }
    
    // 设置光标样式
    if ((isOnLeftEdge && isOnTopEdge) || (isOnRightEdge && isOnBottomEdge)) {
        // 使用标准的对角线光标
        [[NSCursor crosshairCursor] set];
        self.resizeEdge = isOnLeftEdge ? 8 : 6; // topleft or bottomright
    } else if ((isOnRightEdge && isOnTopEdge) || (isOnLeftEdge && isOnBottomEdge)) {
        // 使用标准的对角线光标
        [[NSCursor crosshairCursor] set];
        self.resizeEdge = isOnRightEdge ? 5 : 7; // topright or bottomleft
    } else if (isOnLeftEdge || isOnRightEdge) {
        // 使用水平调整光标
        [[NSCursor resizeLeftRightCursor] set];
        self.resizeEdge = isOnLeftEdge ? 4 : 2; // left or right
    } else if (isOnTopEdge || isOnBottomEdge) {
        // 使用垂直调整光标
        [[NSCursor resizeUpDownCursor] set];
        self.resizeEdge = isOnTopEdge ? 1 : 3; // top or bottom
    } else {
        [[NSCursor arrowCursor] set];
        self.resizeEdge = 0;
    }
}

// 处理鼠标按下事件，开始调整大小
- (void)mouseDownOnWindow:(NSWindow *)window event:(NSEvent *)event {
    // 首先检查是否在拖拽区域内
    NSPoint mouseLocation = [window convertPointFromScreen:[NSEvent mouseLocation]];
    BOOL isInDragRegion = NO;
    if (self.delegate && [self.delegate respondsToSelector:@selector(isPointInDragRegion:)]) {
        isInDragRegion = [self.delegate isPointInDragRegion:mouseLocation];
    }
    
    // 如果在拖拽区域内且不在边缘，则不启动调整大小
    if (isInDragRegion && self.resizeEdge == 0) {
        return;
    }
    
    // 如果不在拖拽区域或在边缘，且有调整边缘，则启动调整大小
    if (self.resizeEdge != 0) {
        self.isResizing = YES;
        self.initialMouseLocation = [NSEvent mouseLocation];
        self.initialFrame = window.frame;
    }
}

// 处理鼠标拖动事件，调整窗口大小
- (void)mouseDraggedOnWindow:(NSWindow *)window event:(NSEvent *)event {
    if (!self.isResizing) return;
    
    NSPoint currentLocation = [NSEvent mouseLocation];
    CGFloat deltaX = currentLocation.x - self.initialMouseLocation.x;
    CGFloat deltaY = currentLocation.y - self.initialMouseLocation.y;
    
    NSRect newFrame = self.initialFrame;
    
    // 根据拖动边缘调整窗口大小
    switch (self.resizeEdge) {
        case 1: // top
            newFrame.size.height += deltaY;
            break;
        case 2: // right
            newFrame.size.width += deltaX;
            break;
        case 3: // bottom
            newFrame.size.height -= deltaY;
            newFrame.origin.y += deltaY;
            break;
        case 4: // left
            newFrame.size.width -= deltaX;
            newFrame.origin.x += deltaX;
            break;
        case 5: // topright
            newFrame.size.width += deltaX;
            newFrame.size.height += deltaY;
            break;
        case 6: // bottomright
            newFrame.size.width += deltaX;
            newFrame.size.height -= deltaY;
            newFrame.origin.y += deltaY;
            break;
        case 7: // bottomleft
            newFrame.size.width -= deltaX;
            newFrame.size.height -= deltaY;
            newFrame.origin.x += deltaX;
            newFrame.origin.y += deltaY;
            break;
        case 8: // topleft
            newFrame.size.width -= deltaX;
            newFrame.size.height += deltaY;
            newFrame.origin.x += deltaX;
            break;
    }
    
    // 设置最小窗口大小
    if (newFrame.size.width < 200) newFrame.size.width = 200;
    if (newFrame.size.height < 150) newFrame.size.height = 150;
    
    [window setFrame:newFrame display:YES];
    
    // 通知 WebView 窗口大小已更改 - 使用更强制的方式更新拖拽区域
    if (window.contentView && [window.contentView isKindOfClass:[WKWebView class]]) {
        WKWebView *webView = (WKWebView *)window.contentView;
        NSString *resizeScript = @"(function() {\n"
                                "    if (window.dispatchEvent) { window.dispatchEvent(new Event('resize')); }\n"
                                "    var dragRegion = document.querySelector('#drag-region');\n"
                                "    if (dragRegion) {\n"
                                "        // 强制更新拖拽区域宽度\n"
                                "        dragRegion.style.width = '';\n"
                                "        void dragRegion.offsetWidth;\n"
                                "        dragRegion.style.width = '100%';\n"
                                "        dragRegion.style.width = '-webkit-fill-available';\n"
                                "    }\n"
                                "})();";
        [webView evaluateJavaScript:resizeScript completionHandler:nil];
    }
}

// 处理鼠标释放事件，结束调整大小
- (void)mouseUpOnWindow:(NSWindow *)window event:(NSEvent *)event {
    if (self.isResizing) {
        self.isResizing = NO;
        self.resizeEdge = 0; // 重要：确保重置 resizeEdge
        [[NSCursor arrowCursor] set];
    }
}

- (void)windowWillClose:(NSNotification *)notification {
    // 当窗口关闭时，退出应用程序
    dispatch_async(dispatch_get_main_queue(), ^{
        [NSApp terminate:nil];
    });
}
@end

@interface WebViewController : NSObject <WKScriptMessageHandler, WebViewControllerDelegate>
@property (nonatomic, strong) NSWindow* window;
@property (nonatomic, strong) WKWebView* webView;
@property (nonatomic, strong) WebViewWindowDelegate* windowDelegate;
@end

@implementation WebViewController
- (void)userContentController:(WKUserContentController *)userContentController 
      didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"dragRegion"]) {
        NSDictionary* body = message.body;
        NSString* type = body[@"type"];
        
        NSLog(@"收到消息: %@", body);
        
        if ([type isEqualToString:@"dragStart"]) {
            // 设置一个标志，表示我们正在从拖拽区域拖拽
            // 这将阻止窗口调整大小操作
            self.windowDelegate.isResizing = NO;
            self.windowDelegate.resizeEdge = 0;
        } else if ([type isEqualToString:@"dragMove"]) {
            // 只有当我们不在调整大小时才处理拖拽
            if (!self.windowDelegate.isResizing) {
                NSNumber* deltaX = body[@"deltaX"];
                NSNumber* deltaY = body[@"deltaY"];
                
                // 检查增量值是否合理，防止异常值导致崩溃
                CGFloat dX = deltaX.doubleValue;
                CGFloat dY = deltaY.doubleValue;
                
                // 限制单次移动的最大距离，防止异常值
                const CGFloat maxDelta = 100.0;
                if (fabs(dX) > maxDelta) dX = (dX > 0) ? maxDelta : -maxDelta;
                if (fabs(dY) > maxDelta) dY = (dY > 0) ? maxDelta : -maxDelta;
                
                // 如果增量太小，忽略它以避免微小移动导致的闪烁
                const CGFloat minDelta = 0.5;
                if (fabs(dX) < minDelta) dX = 0;
                if (fabs(dY) < minDelta) dY = 0;
                
                // 如果没有实际移动，直接返回
                if (dX == 0 && dY == 0) return;
                
                
                // 获取当前窗口位置
                NSRect windowFrame = self.window.frame;
                
                // 计算新位置 - 使用整数坐标避免亚像素渲染导致的闪烁
                NSPoint newOrigin = windowFrame.origin;
                newOrigin.x += dX;
                newOrigin.y -= dY; // 注意：屏幕坐标系Y轴与网页坐标系相反
                
                // 四舍五入到整数坐标
                newOrigin.x = round(newOrigin.x);
                newOrigin.y = round(newOrigin.y);
                
                // 在主线程上设置窗口位置，确保UI更新平滑
                dispatch_async(dispatch_get_main_queue(), ^{
                    @try {
                        [self.window setFrameOrigin:newOrigin];
                    } @catch (NSException *exception) {
                        NSLog(@"设置窗口位置时发生异常: %@", exception);
                    }
                });
            }
        } else if ([type isEqualToString:@"windowControl"]) {
            NSString* action = body[@"action"];
            
            if ([action isEqualToString:@"close"]) {
                NSLog(@"关闭窗口");
                // 先关闭窗口
                [self.window close];
                // 然后退出应用程序
                dispatch_async(dispatch_get_main_queue(), ^{
                    [NSApp terminate:nil];
                });
            } else if ([action isEqualToString:@"minimize"]) {
                NSLog(@"最小化窗口");
                // 使用系统级API直接发送最小化命令
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSApplication sharedApplication] hide:nil];
                });
            } else if ([action isEqualToString:@"maximize"]) {
                NSLog(@"最大化/还原窗口");
                // 使用更直接的方法来切换窗口大小
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSRect screenRect = [[NSScreen mainScreen] visibleFrame];
                    NSRect windowRect = [self.window frame];
                    
                    // 检查窗口是否已经最大化（通过比较窗口大小和屏幕大小）
                    BOOL isMaximized = (windowRect.size.width >= screenRect.size.width * 0.9 &&
                                       windowRect.size.height >= screenRect.size.height * 0.9);
                    
                    if (isMaximized) {
                        // 如果已经最大化，则还原到之前保存的大小
                        // 这里使用一个合理的默认大小
                        NSRect newRect = NSMakeRect(
                            screenRect.origin.x + screenRect.size.width/4,
                            screenRect.origin.y + screenRect.size.height/4,
                            screenRect.size.width/2,
                            screenRect.size.height/2
                        );
                        [self.window setFrame:newRect display:YES animate:YES];
                        NSLog(@"窗口已还原");
                    } else {
                        // 最大化窗口（留一点边距）
                        NSRect newRect = NSMakeRect(
                            screenRect.origin.x + 10,
                            screenRect.origin.y + 10,
                            screenRect.size.width - 20,
                            screenRect.size.height - 20
                        );
                        [self.window setFrame:newRect display:YES animate:YES];
                        NSLog(@"窗口已最大化");
                    }
                });
            }
        }
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"loading"]) {
        if (!self.webView.loading) {  // 页面加载完成
            NSLog(@"页面加载完成，开始注入脚本");
            
            // 注入 JavaScript 来处理拖拽和窗口控制
            NSString* js = @"(function() {\n"
                          "    console.log('正在设置拖拽区域和窗口控制');\n"
                          "    var dragRegion = document.querySelector('#drag-region');\n"
                          "    console.log('查找拖拽区域:', dragRegion);\n"
                          "    if (dragRegion) {\n"
                          "        console.log('找到拖拽区域元素');\n"
                          "        dragRegion.style.cursor = 'move';\n"
                          "        var isDragging = false;\n"
                          "        var lastX = 0, lastY = 0;\n"
                          "        var edgeSize = 8;\n"
                          "\n"
                          "        function isInResizeArea(e) {\n"
                          "            // 获取窗口大小\n"
                          "            var windowWidth = window.innerWidth;\n"
                          "            var windowHeight = window.innerHeight;\n"
                          "            var rect = dragRegion.getBoundingClientRect();\n"
                          "\n"
                          "            // 检查是否在窗口边缘\n"
                          "            var isOnEdge = (e.clientX <= edgeSize || \n"
                          "                          e.clientX >= windowWidth - edgeSize || \n"
                          "                          e.clientY <= edgeSize || \n"
                          "                          e.clientY >= windowHeight - edgeSize);\n"
                          "\n"
                          "            // 如果在拖拽区域内，只有当点也在窗口边缘时才认为是调整区域\n"
                          "            if (e.clientX >= rect.left && e.clientX <= rect.right && \n"
                          "                e.clientY >= rect.top && e.clientY <= rect.bottom) {\n"
                          "                return isOnEdge;\n"
                          "            }\n"
                          "\n"
                          "            // 如果不在拖拽区域内，但在窗口边缘，也认为是调整区域\n"
                          "            return isOnEdge;\n"
                          "        }\n"
                          "\n"
                          "        function handleDrag(e) {\n"
                          "            if (!isDragging) return;\n"
                          "            var deltaX = e.screenX - lastX;\n"
                          "            var deltaY = e.screenY - lastY;\n"
                          "\n"
                          "            // 如果移动太小，不处理以避免闪烁\n"
                          "            if (Math.abs(deltaX) < 0.5 && Math.abs(deltaY) < 0.5) return;\n"
                          "\n"
                          "            lastX = e.screenX;\n"
                          "            lastY = e.screenY;\n"
                          "            console.log('拖拽中:', deltaX, deltaY);\n"
                          "            window.webkit.messageHandlers.dragRegion.postMessage({\n"
                          "                type: 'dragMove',\n"
                          "                deltaX: deltaX,\n"
                          "                deltaY: deltaY\n"
                          "            });\n"
                          "        }\n"
                          "\n"
                          "        dragRegion.addEventListener('mousedown', function(e) {\n"
                          "            // 如果在调整区域内，不启动拖拽\n"
                          "            if (isInResizeArea(e)) {\n"
                          "                console.log('在调整区域内，不启动拖拽');\n"
                          "                return;\n"
                          "            }\n"
                          "\n"
                          "            // 检查是否点击了窗口控制按钮\n"
                          "            var target = e.target;\n"
                          "            while (target && !target.classList.contains('window-control-button')) {\n"
                          "                target = target.parentElement;\n"
                          "            }\n"
                          "            if (target && target.classList.contains('window-control-button')) {\n"
                          "                console.log('点击了窗口控制按钮');\n"
                          "                var action = target.getAttribute('data-action');\n"
                          "                window.webkit.messageHandlers.dragRegion.postMessage({\n"
                          "                    type: 'windowControl',\n"
                          "                    action: action\n"
                          "                });\n"
                          "                return;\n"
                          "            }\n"
                          "\n"
                          "            // 设置一个标志，表示我们正在拖拽\n"
                          "            window.webkit.messageHandlers.dragRegion.postMessage({\n"
                          "                type: 'dragStart'\n"
                          "            });\n"
                          "\n"
                          "            console.log('鼠标按下');\n"
                          "            isDragging = true;\n"
                          "            lastX = e.screenX;\n"
                          "            lastY = e.screenY;\n"
                          "\n"
                          "            // 使用 requestAnimationFrame 来平滑拖拽\n"
                          "            var rafDrag = function(timestamp) {\n"
                          "                if (!isDragging) return;\n"
                          "                document.addEventListener('mousemove', handleDrag, {passive: true});\n"
                          "                requestAnimationFrame(rafDrag);\n"
                          "            };\n"
                          "            requestAnimationFrame(rafDrag);\n"
                          "        }, {passive: true});\n"
                          "\n"
                          "        document.addEventListener('mouseup', function() {\n"
                          "            if (isDragging) {\n"
                          "                console.log('结束拖拽');\n"
                          "                isDragging = false;\n"
                          "                document.removeEventListener('mousemove', handleDrag);\n"
                          "            }\n"
                          "        }, {passive: true});\n"
                          "\n"
                          "        console.log('拖拽区域和窗口控制设置完成');\n"
                          "    } else {\n"
                          "        console.log('未找到拖拽区域元素');\n"
                          "    }\n"
                          "})();";
            
            [self.webView evaluateJavaScript:js completionHandler:^(id result, NSError *error) {
                if (error) {
                    NSLog(@"脚本注入错误: %@", error);
                } else {
                    NSLog(@"脚本注入成功");
                }
            }];
            
            // 移除观察者
            [self.webView removeObserver:self forKeyPath:@"loading"];
        }
    }
}

- (void)setupResizeHandling {
    // 设置窗口事件监听
    NSWindow *window = self.window;
    
    // 创建事件监听器
    NSEvent* (^mouseMoved)(NSEvent*) = ^NSEvent* (NSEvent* event) {
        [self.windowDelegate mouseMovedOnWindow:window event:event];
        return event;
    };
    
    NSEvent* (^mouseDown)(NSEvent*) = ^NSEvent* (NSEvent* event) {
        [self.windowDelegate mouseDownOnWindow:window event:event];
        return event;
    };
    
    NSEvent* (^mouseDragged)(NSEvent*) = ^NSEvent* (NSEvent* event) {
        [self.windowDelegate mouseDraggedOnWindow:window event:event];
        return event;
    };
    
    NSEvent* (^mouseUp)(NSEvent*) = ^NSEvent* (NSEvent* event) {
        [self.windowDelegate mouseUpOnWindow:window event:event];
        return event;
    };
    
    // 添加事件监听
    [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskMouseMoved handler:mouseMoved];
    [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDown handler:mouseDown];
    [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDragged handler:mouseDragged];
    [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskLeftMouseUp handler:mouseUp];
    
    // 添加窗口大小变化的通知监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(windowDidResize:)
                                                 name:NSWindowDidResizeNotification
                                               object:window];
}

// 实现协议方法
- (BOOL)isPointInDragRegion:(NSPoint)point {
    // 获取拖拽区域的位置和大小
    // 这里假设拖拽区域是窗口顶部的一个区域，高度为40像素
    CGFloat dragRegionHeight = 40.0;
    
    // 检查点击位置是否在拖拽区域内
    // 注意：这里需要排除窗口边缘的调整区域
    CGFloat edgeSize = 8.0; // 与边缘检测区域大小相同
    CGFloat windowWidth = self.window.contentView.frame.size.width;
    CGFloat windowHeight = self.window.contentView.frame.size.height;
    
    // 点在顶部拖拽区域，但不在窗口边缘
    BOOL isInDragRegion = (point.y >= windowHeight - dragRegionHeight) && 
                          (point.x >= edgeSize) && 
                          (point.x <= windowWidth - edgeSize) &&
                          (point.y <= windowHeight - edgeSize);
    
    return isInDragRegion;
}

- (void)windowDidResize:(NSNotification *)notification {
    // 强制更新拖拽区域宽度
    NSString *updateScript = @"(function() {\n"
                            "    var dragRegion = document.querySelector('#drag-region');\n"
                            "    if (dragRegion) {\n"
                            "        // 强制更新拖拽区域宽度\n"
                            "        dragRegion.style.width = '';\n"
                            "        void dragRegion.offsetWidth;\n"
                            "        dragRegion.style.width = '100%';\n"
                            "        dragRegion.style.width = '-webkit-fill-available';\n"
                            "    }\n"
                            "})();";
    [self.webView evaluateJavaScript:updateScript completionHandler:nil];
}
@end

struct CustomWebView {
    WebViewController* controller;
};

CustomWebView* webview_create(WebViewConfig config) {
    CustomWebView* webview = (CustomWebView*)malloc(sizeof(CustomWebView));
    WebViewController* controller = [[WebViewController alloc] init];
    
    // 创建窗口样式
    NSUInteger windowStyle = NSWindowStyleMaskBorderless;  // 默认使用无边框样式
    
    if (!config.borderless) {
        // 如果不需要无边框，则使用标准样式
        windowStyle = NSWindowStyleMaskTitled | 
                     NSWindowStyleMaskClosable | 
                     NSWindowStyleMaskMiniaturizable |
                     NSWindowStyleMaskResizable;
    } else {
        // 即使是无边框窗口，也需要添加这些样式以支持最小化和缩放操作
        windowStyle |= NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable;
    }
    
    // 创建窗口
    NSRect frame = NSMakeRect(config.x, config.y, config.width, config.height);
    NSWindow* window = [[NSWindow alloc] initWithContentRect:frame
                                                  styleMask:windowStyle
                                                    backing:NSBackingStoreBuffered
                                                      defer:NO];
    
    // 设置透明
    if (config.transparent) {
        window.backgroundColor = [NSColor clearColor];
        window.opaque = NO;
    } else {
        window.backgroundColor = [NSColor whiteColor];  // 设置默认背景色
    }
    
    // 设置窗口标题栏隐藏
    if (config.borderless) {
        [window setTitlebarAppearsTransparent:YES];
        [window setTitleVisibility:NSWindowTitleHidden];
        
        window.hasShadow = NO;
        window.backgroundColor = [NSColor clearColor];
        [window setOpaque:NO];
    }
    
    // 设置标题（即使隐藏也设置，为了程序标识）
    window.title = @(config.title);
    window.alphaValue = config.alpha;
    
    // 设置窗口关闭时的行为
    window.releasedWhenClosed = NO;
    
    // 创建并设置窗口代理
    WebViewWindowDelegate* windowDelegate = [[WebViewWindowDelegate alloc] init];
    windowDelegate.delegate = controller; // 使用协议代理而不是直接引用
    window.delegate = windowDelegate;
    controller.windowDelegate = windowDelegate;
    
    // 创建 WebView
    WKWebViewConfiguration* webConfig = [[WKWebViewConfiguration alloc] init];
    WKWebView* webView = [[WKWebView alloc] initWithFrame:frame configuration:webConfig];
    
    // 隐藏滚动条 - 更新实现
    if (config.hide_scrollbars) {
        // 获取 WKWebView 的滚动视图
        NSScrollView *scrollView = [webView enclosingScrollView];
        
        // 隐藏滚动条指示器
        [scrollView setHasHorizontalScroller:NO];
        [scrollView setHasVerticalScroller:NO];
        
        // 注入 CSS 来隐藏所有类型的滚动条
        NSString* css = @"*::-webkit-scrollbar { display: none !important; }"
                       "* { scrollbar-width: none !important; }"
                       "* { -ms-overflow-style: none !important; }"
                       "* { overflow: -moz-scrollbars-none !important; }";
        
        WKUserScript* script = [[WKUserScript alloc] initWithSource:css 
                                                     injectionTime:WKUserScriptInjectionTimeAtDocumentStart 
                                                  forMainFrameOnly:NO];
        [webView.configuration.userContentController addUserScript:script];
        
        // 添加额外的 JavaScript 来处理动态加载的内容
        NSString* js = @"document.addEventListener('DOMContentLoaded', function() {"
                      "   var style = document.createElement('style');"
                      "   style.type = 'text/css';"
                      "   style.innerHTML = '*::-webkit-scrollbar { display: none !important; }';"
                      "   document.head.appendChild(style);"
                      "});";
        
        WKUserScript* jsScript = [[WKUserScript alloc] initWithSource:js
                                                       injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
                                                    forMainFrameOnly:NO];
        [webView.configuration.userContentController addUserScript:jsScript];
    }
    
    window.contentView = webView;
    
    controller.window = window;
    controller.webView = webView;
    webview->controller = controller;
    
    // 设置窗口级别和行为
    [window setLevel:NSNormalWindowLevel];
    [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
    [window center];  // 居中显示
    
    // 设置大小调整处理
    [controller setupResizeHandling];
    
    return webview;
}

void webview_load_url(CustomWebView* webview, const char* url) {
    NSURL* nsurl = [NSURL URLWithString:@(url)];
    NSURLRequest* request = [NSURLRequest requestWithURL:nsurl];
    [webview->controller.webView loadRequest:request];
}

void webview_load_html(CustomWebView* webview, const char* html) {
    [webview->controller.webView loadHTMLString:@(html) baseURL:nil];
}

void webview_set_alpha(CustomWebView* webview, float alpha) {
    webview->controller.window.alphaValue = alpha;
}

void webview_set_title(CustomWebView* webview, const char* title) {
    webview->controller.window.title = @(title);
}

void webview_set_size(CustomWebView* webview, int width, int height) {
    NSRect frame = webview->controller.window.frame;
    frame.size.width = width;
    frame.size.height = height;
    [webview->controller.window setFrame:frame display:YES];
}

void webview_set_position(CustomWebView* webview, int x, int y) {
    NSRect frame = webview->controller.window.frame;
    frame.origin.x = x;
    frame.origin.y = y;
    [webview->controller.window setFrameOrigin:frame.origin];
}

void webview_show(CustomWebView* webview) {
    [webview->controller.window makeKeyAndOrderFront:nil];
}

void webview_hide(CustomWebView* webview) {
    [webview->controller.window orderOut:nil];
}

void webview_destroy(CustomWebView* webview) {
    [webview->controller.window close];
    free(webview);
}

void webview_init(void) {
    // 确保在主线程运行
    if (![NSThread isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            webview_init();
        });
        return;
    }
    
    // 初始化 NSApplication
    [NSApplication sharedApplication];
    
    // 设置应用代理
    id appDelegate = [[NSObject alloc] init];
    [NSApp setDelegate:appDelegate];
    
    // 设置激活策略
    [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
    
    // 完成初始化
    [NSApp finishLaunching];
    
    // 激活应用
    [NSApp activateIgnoringOtherApps:YES];
}

void webview_run(void) {
    // 确保在主线程运行
    if (![NSThread isMainThread]) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            webview_run();
        });
        return;
    }
    
    NSEvent* (^handler)(NSEvent*) = ^NSEvent* (NSEvent* event) {
        if ([event type] == NSEventTypeKeyDown) {
            if (([event modifierFlags] & NSEventModifierFlagCommand) && 
                [[event charactersIgnoringModifiers] isEqualToString:@"q"]) {
                [NSApp terminate:nil];
            }
        }
        return event;
    };
    
    [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:handler];
    
    // 运行主事件循环
    [NSApp run];
}

void webview_set_drag_region(CustomWebView* webview, const char* css_selector) {
    NSLog(@"设置拖拽区域: %s", css_selector);
    
    // 等待页面加载完成后再注入脚本
    [webview->controller.webView.configuration.userContentController 
        addScriptMessageHandler:webview->controller 
        name:@"dragRegion"];
    
    // 创建加载完成的观察者
    [webview->controller.webView addObserver:webview->controller
                                forKeyPath:@"loading"
                                   options:NSKeyValueObservingOptionNew
                                   context:NULL];
}

void webview_load_html_file(CustomWebView* webview, const char* filepath) {
    // 读取HTML文件内容
    NSString* path = @(filepath);
    NSError* error = nil;
    NSString* html = [NSString stringWithContentsOfFile:path 
                                              encoding:NSUTF8StringEncoding 
                                                 error:&error];
    
    if (error) {
        NSLog(@"读取HTML文件失败: %@", error);
        return;
    }
    
    // 获取文件所在目录作为基础URL
    NSURL* baseURL = [NSURL fileURLWithPath:[path stringByDeletingLastPathComponent]];
    
    // 加载HTML内容
    [webview->controller.webView loadHTMLString:html baseURL:baseURL];
} 